//
//  SQLowAuctionDetailViewController.m
//  pai
//
//  Created by pro on 14-11-10.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQLowAuctionDetailViewController.h"
#import "SQLowRuleViewController.h"
#import "SQPlaceBidView.h"
#import "Global.h"
#import "SQLoginViewController.h"
#import "UIImageView+WebCache.h"

@interface SQLowAuctionDetailViewController ()

@end

@implementation SQLowAuctionDetailViewController
@synthesize scrollView = _scrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"商品详情"];
    
    //[self initview];
    NSLog(@"viewDidLoad");
}

-(void)getInfo
{
    NSLog(@"getInfo");
    NSLog(@"self.item.sku_code:%s",self.item.sku_code);
    auct_sku_detail_t detail;
    detail.base.msgtype = 1020;
    detail.base.len = sizeof(detail);
    detail.base.error = 0;
    
    strcpy(detail.sku_code, self.item.sku_code);
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&detail length:sizeof(detail)];
    
    [super sendData:msgData tag:1 withHUD:YES];
}

-(void)initview:(ack_auct_sku_detail_t)detail
{
    NSString* namestr = [NSString stringWithUTF8String:self.item.sku_name];
    NSString* pricestr = [NSString stringWithFormat:@"%d",detail.cost];
    NSString* personstr = @"888";
    NSArray *keyarray = [[NSString stringWithUTF8String:detail.attri_keys] componentsSeparatedByString:@"|"];
    NSArray *valuearray = [[NSString stringWithUTF8String:detail.attri_values] componentsSeparatedByString:@"|"];
    NSMutableString* contentstr = [NSMutableString string];
    for (NSInteger i=0; i<keyarray.count-1; i++) {
        [contentstr appendFormat:@"%@:%@\n",[keyarray objectAtIndex:i],[valuearray objectAtIndex:i]];
    }
//    NSLog(@"%@",[NSString stringWithUTF8String:detail.attri_keys]);
//    NSLog(@"%@",keyarray);
//    NSLog(@"%@",[NSString stringWithUTF8String:detail.attri_values]);
//    NSLog(@"%@",valuearray);
//    NSLog(@"contentstr:%@",contentstr);
   // NSString* imageName = [NSString stringWithFormat:@"%@%@",IMAGESERVICE,[self.imageDic objectForKey:@"detail"]];
    self.imageUrls =[self.imageDic objectForKey:@"intro"];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.MyNavigationBar.frame.origin.y+self.MyNavigationBar.frame.size.height, 320, [[UIScreen  mainScreen] bounds].size.height - 44 - self.MyNavigationBar.frame.origin.y-self.MyNavigationBar.frame.size.height)];
    [_scrollView setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    [self.view addSubview:_scrollView];
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = NO;
    _scrollView.scrollEnabled = YES;
    
    //图片
    NSString* url = [NSString stringWithFormat:@"%@%@",IMAGESERVICE,[self.imageDic objectForKey:@"detail"]];
    //NSArray* imgarr =[self.imageDic objectForKey:@"detail"];
    //[self titleimage:imgarr];
    UIImageView *imageView = [[UIImageView alloc] init];
    NSLog(@"ljjjj:%@",url);
    [imageView setImageWithURL:[NSURL URLWithString:url]];
    imageView.frame = CGRectMake(0, 0, 320, 320);
    [_scrollView addSubview:imageView];
    NSInteger viewHeight = 320;
    //名称
    UILabel* nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, viewHeight, 300, 60)];
    [nameLabel setText:namestr];
    NSLog(@"namestr:%@",namestr);
    nameLabel.textAlignment = UITextAlignmentCenter;
    nameLabel.numberOfLines = 2;
    [_scrollView addSubview:nameLabel];
    viewHeight+=60;
    //价格
    UILabel* priceLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, viewHeight, 200, 20)];
    NSMutableAttributedString* price = [[NSMutableAttributedString alloc]initWithString:[[NSString alloc] initWithFormat:@"商品市场价：%@豆",pricestr]];
    [price addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,6)];
    [price addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,[price length]-7)];
    [price addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange([price length]-1,1)];
    priceLabel.attributedText = price;
    [_scrollView addSubview:priceLabel];
    
    //时间
    [self initTime];
    
    //人数
    UILabel* personLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, viewHeight+50, 200, 20)];
    NSMutableAttributedString* person = [[NSMutableAttributedString alloc]initWithString:[[NSString alloc] initWithFormat:@"已参拍人数：%@人",personstr]];
    [person addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,6)];
    [person addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,[person length]-7)];
    [person addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange([person length]-1,1)];
    personLabel.attributedText = person;
    [_scrollView addSubview:personLabel];
    
    //规则按钮
    UIButton* ruleBtn = [[UIButton alloc]initWithFrame:CGRectMake(230, viewHeight, 75, 75)];
    [ruleBtn setBackgroundImage:[UIImage imageNamed:@"rule_btn"] forState:UIControlStateNormal];
    [ruleBtn addTarget:self action:@selector(onActionRules:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:ruleBtn];
    viewHeight+= 80;
    
    //竞拍按钮
    self.auctionBtn = [[UIButton alloc]initWithFrame:CGRectMake(80, viewHeight, 160, 40)];
    [self.auctionBtn setTitle:@"我要出价" forState:UIControlStateNormal];
    [self.auctionBtn addTarget:self action:@selector(onActionPlaceBid:) forControlEvents:UIControlEventTouchUpInside];
    [self.auctionBtn setBackgroundColor:[UIColor colorWithRed:1 green:40/255.0 blue:40/255.0 alpha:1]];
    [self.auctionBtn setHidden:YES];
    [_scrollView addSubview:self.auctionBtn];
    viewHeight+= 50;
    
    //商品详情
    UILabel* titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, viewHeight, 320, 30)];
    [titleLabel setText:@"  商品详情"];
    [titleLabel setBackgroundColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1]];
    [titleLabel setTextColor:[UIColor whiteColor]];
    titleLabel.textAlignment = UITextAlignmentLeft;
    [_scrollView addSubview:titleLabel];
    viewHeight+= 30;
    
    UILabel* contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, viewHeight, 300, 200)];
    [contentLabel setNumberOfLines:0];
    [contentLabel setTextColor:[UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1]];
    [contentLabel setFont:[UIFont systemFontOfSize:14]];
    [contentLabel setText:contentstr];
    [contentLabel sizeToFit];
    [_scrollView addSubview:contentLabel];
    
    self.imageheight = contentLabel.frame.origin.y+contentLabel.frame.size.height;
    
    if (self.imageUrls.count > 0) {
        self.imageindex = 0;
        [self loadimage];
    }
    
    _scrollView.contentSize = CGSizeMake(320,self.imageheight);
    
    self.placeBidBackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, self.MyNavigationBar.frame.origin.y+self.MyNavigationBar.frame.size.height, 320, [[UIScreen  mainScreen] bounds].size.height - 44 - self.MyNavigationBar.frame.origin.y-self.MyNavigationBar.frame.size.height)];
    [self.placeBidBackgroundView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5]];
    [self.placeBidBackgroundView setHidden:YES];
    [self.view addSubview:self.placeBidBackgroundView];
    
    self.placeBidView = [[SQPlaceBidView alloc]initWithstartPrice:[NSString stringWithFormat:@"%d",detail.price] endPrice:[NSString stringWithFormat:@"%d",detail.cost]];
    self.placeBidView.frame = CGRectMake((_scrollView.frame.size.width - self.placeBidView.frame.size.width)/2, (_scrollView.frame.size.height - self.placeBidView.frame.size.height)/2, self.placeBidView.frame.size.width, self.placeBidView.frame.size.height);
    self.placeBidView.delegate =self;
    [self.placeBidBackgroundView addSubview:self.placeBidView];
}
-(void)titleimage:(NSArray*)arr
{
    _imagescrolView = [[UIScrollView alloc] init];
    [_imagescrolView setFrame:CGRectMake(0, 0, 320, 320)];
    [_imagescrolView setContentSize:CGSizeMake(320*arr.count, 320)];
    _imagescrolView.pagingEnabled = YES;
    _imagescrolView.delegate = self;
    _imagescrolView.bounces = NO;
    [_scrollView addSubview:_imagescrolView];
    
    for(int i=0;i<arr.count;i++)
    {
        UIImageView *imageView = [[UIImageView alloc] init];
        NSString* url = [NSString stringWithFormat:@"%@%@",IMAGESERVICE,[arr objectAtIndex:i]];
        [imageView setImageWithURL:[NSURL URLWithString:url]];
        imageView.frame = CGRectMake(320*i, 0, 320, 320);
        [_imagescrolView addSubview:imageView];
        
    }
    _page=[[UIPageControl alloc]initWithFrame:CGRectMake(250, 280, 100, 30)];
    //设置有多少个小白点
    _page.numberOfPages=arr.count;
    //设置背景色
    //page.backgroundColor=[UIColor redColor];
    //设置起始小白点是哪个
    _page.currentPage=0;
    //设置小白颜色
    _page.pageIndicatorTintColor=[UIColor greenColor];
    _page.currentPageIndicatorTintColor=[UIColor yellowColor];
    [_scrollView addSubview:_page];
    
    //通常广告是自己动
    _imageTimer=[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
}
-(void)timerClick
{
    CGPoint point = _imagescrolView.contentOffset;
    if (point.x==_imagescrolView.contentSize.width - 320) {
        [UIView animateWithDuration:0.5 animations:^{
            _imagescrolView.contentOffset = CGPointMake(0, 0);
        }];
        _page.currentPage=0;
    }else
    {
        [UIView animateWithDuration:0.5 animations:^{
            _imagescrolView.contentOffset = CGPointMake(point.x+320, 0);
        }];
        _page.currentPage =(int)(point.x+320)/320;
    }
}
-(void)loadimage
{
    UIImageView* imgView = [[UIImageView alloc]init];
    NSString* imageUrl = [NSString stringWithFormat:@"%@%@",IMAGESERVICE,[self.imageUrls objectAtIndex:self.imageindex]];
    [imgView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:nil completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType)
     
     {
         __block UIImageView *tempview = imgView;
         int x=image.size.width;
         int y=image.size.height;
         CGFloat height = 320.0/x*y;
         //自适应图片宽高比例
         tempview.frame = CGRectMake(0, self.imageheight, 320, height);
         tempview.contentMode = UIViewContentModeScaleAspectFit;
         self.imageheight += height;
         _scrollView.contentSize = CGSizeMake(320,self.imageheight);
         if (self.imageindex < self.imageUrls.count - 1) {
             self.imageindex ++;
             [self loadimage];
         }
     }];
    [_scrollView addSubview:imgView];
}
-(void)initTime
{
    NSDate* now = [NSDate date];
    
    self.beginTime = self.item.stdate;
    self.endTime = self.item.eddate;
    self.serviceTime = [now timeIntervalSince1970];
    self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 405, 200, 20)];
    [_scrollView addSubview:self.timeLabel];
    self.countLabel = [[UILabel alloc]initWithFrame:CGRectMake(120, 405, 90, 20)];
    [_scrollView addSubview:self.countLabel];
    [self.countLabel setTextColor:[UIColor whiteColor]];
    self.countLabel.textAlignment = UITextAlignmentCenter;
    self.countLabel.backgroundColor = [UIColor colorWithRed:81/255.0 green:84/255.0 blue:90/255.0 alpha:1];
    [self updateTime:nil];
   self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
}
-(void)updateTime:(NSTimer*)timer
{
    self.serviceTime ++ ;
    NSInteger time = 0;
    if (self.serviceTime > self.beginTime && self.serviceTime < self.endTime) {
        [self.timeLabel setText:@"竞拍倒计时:"];
        self.auctionBtn.hidden = NO;
        time = self.endTime - self.serviceTime;
    }
    else if(self.serviceTime<self.beginTime)
    {
        [self.timeLabel setText:@"开始倒计时:"];
        time = self.beginTime - self.serviceTime;
        self.auctionBtn.hidden = YES;
    }else if (self.serviceTime > self.endTime)
    {
        [self.timeLabel setText:@"竞拍倒计时:"];
        self.auctionBtn.hidden = YES;
        time = 0;
        [self.timer invalidate];
        self.timer = nil;
    }
    [self showtime:time];
}

-(void)showtime:(NSInteger)time
{
    NSInteger hour = time/3600;
    time = time%3600;
    NSInteger min = time/60;
    time = time%60;
    NSInteger sec = time;
    NSMutableString* str = [[NSMutableString alloc]init];
    if (hour < 10) {
        [str appendString:[[NSString alloc]initWithFormat:@"0%d:",hour]];
    }
    else{
        [str appendString:[[NSString alloc]initWithFormat:@"%d:",hour]];
    }
    if (min < 10) {
        [str appendString:[[NSString alloc]initWithFormat:@"0%d:",min]];
    }
    else{
        [str appendString:[[NSString alloc]initWithFormat:@"%d:",min]];
    }
    if (sec < 10) {
        [str appendString:[[NSString alloc]initWithFormat:@"0%d",sec]];
    }
    else{
        [str appendString:[[NSString alloc]initWithFormat:@"%d",sec]];
    }
    [self.countLabel setText:str];
}
-(void)onActionRules:(UIButton*)btn
{
    SQLowRuleViewController* rvc = [[SQLowRuleViewController alloc]init];
    [self.navigationController pushViewController:rvc animated:YES];
}
-(void)onActionBack:(UIButton*)button
{
    NSLog(@"onaction");
    [super onActionBack:button];
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    if (_imageTimer) {
        [_imageTimer invalidate];
        _imageTimer = nil;
    }
}
-(void)onActionPlaceBid:(UIButton*)button
{
    if ([Global instance].logined) {
        if (self.placeBidBackgroundView) {
            [self.placeBidBackgroundView setHidden:NO];
        }
    }
    else{
        SQLoginViewController* lvc = [[SQLoginViewController alloc]init];
        [self.navigationController pushViewController:lvc animated:YES];
    }
}
-(void)PlaceBidCancle
{
    if (self.placeBidBackgroundView) {
        [self.placeBidBackgroundView setHidden:YES];
    }
}
-(void)PlaceBidSumbmit:(NSString *)price
{
    if (self.placeBidBackgroundView) {
        [self.placeBidBackgroundView setHidden:YES];
    }
    NSLog(@"出价%@",price);
    
    biz_auction_t auction;
    auction.base.msgtype = 8016;
    auction.base.len = sizeof(auction);
    auction.base.error = 0;
    
    auction.auctprice = [price intValue];
    strcpy(auction.username, [[Global instance].userinfo.username UTF8String]);
    NSLog(@"pai username:%@",[Global instance].userinfo.username);
    strcpy(auction.serialnum, self.item.serialnum);
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&auction length:sizeof(auction)];
    
    [super sendData:msgData tag:2 withHUD:YES];
}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    if (tag == 1) {
        ack_auct_sku_detail_t adetail;
        [data getBytes:&adetail length:sizeof(adetail)];
        NSString* msg = @"";
        if (adetail.base.error == 3063) {
            msg = @"找不到该竞拍物品";
            [self.HUD showAnimated:YES whileExecutingBlock:^{
                self.HUD.labelText = msg;
                sleep(2);
                [self.HUD show:NO];
            } completionBlock:^{
            }];
        }else if(adetail.base.error == ACS_SUCCESS){
            [self.HUD showAnimated:YES whileExecutingBlock:^{
                [self.HUD show:NO];
            } completionBlock:^{
                [self initview:adetail];
            }];
        }
    }
    else if(tag == 2)
    {
        acs_base_t base;
        [data getBytes:&base length:sizeof(base)];
        NSString* msg = @"";
        if(base.error == ACS_SUCCESS)
        {
            msg = @"竞价成功";
        }
        else if (base.error == 3030)
        {
            msg = @"重复出价";
        }
        else if (base.error == 3032)
        {
            msg = @"余额不足";
        }
        else if (base.error == 3031)
        {
            msg = @"已出价三次";
        }
        else if (base.error == 3034)
        {
            msg = @"竞拍未开始";
        }
        else if (base.error == 3036)
        {
            msg = @"无效的价格";
        }
        else if (base.error == 3038)
        {
            msg = @"出价失败";
        }
        else if (base.error == 3040)
        {
            msg = @"竞拍成功，但已有人出相同价格";
        }
        else{
            msg = @"未知错误，请重试！";
        }
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            self.HUD.labelText = msg;
            sleep(2);
            [self.HUD show:NO];
        } completionBlock:^{
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
